package cn.jdemo.pattern.lazy_loading;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.Supplier;

/**
 * 推荐
 * This lazy loader is thread safe and more efficient than {@link HolderJdk8}. It utilizes
 * Java 8 functional interface {@link Supplier} as {@link Heavy} factory.
 *
 * @date 2021/1/19
 */
public class HolderJdk8 {

    private final static Logger logger = LoggerFactory.getLogger(HolderJdk8.class);

    private Supplier<Heavy> heavy = this::createAndCacheHeavy;

    HolderJdk8(){
        logger.info("HolderJdk8 created");
    }

    Heavy getHeavy(){
        return heavy.get();
    }

    private synchronized Heavy createAndCacheHeavy(){

        class HeavyFactory implements Supplier<Heavy>{
            private final Heavy heavyInstance = new Heavy();
            @Override
            public Heavy get() {
                return heavyInstance;
            }
        }

        // ???
        if (! HeavyFactory.class.isInstance(heavy)) {
            heavy = new HeavyFactory();
        }
        return heavy.get();
    }
}
